package com.heima;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class TransactionAdvice {

    DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    DataSourceTransactionManager transactionManager = null;
    DefaultTransactionDefinition definition = null;
    TransactionStatus transactionStatus = null;


    public void before(){
        //传入数据源参数
        transactionManager = new DataSourceTransactionManager(dataSource);
        //定义事务的具体信息
        definition = new DefaultTransactionDefinition();
        //开启事务，返回事务的状态
        transactionStatus = transactionManager.getTransaction(definition);
    }

    public void afterReturning(){
        //提交事务
        transactionManager.commit(transactionStatus);
    }

    public void afterThrowing(){
        //出现异常回滚事务
        transactionManager.rollback(transactionStatus);
    }

}
